package org.holynite.fieldmanage.listener

import javax.faces.context.FacesContext
import javax.faces.event.PhaseEvent
import javax.faces.event.PhaseId
import javax.faces.event.PhaseListener
import javax.servlet.http.HttpSession

/**
 * Created by midnite on 15/1/8.
 */
class AuthorizationListener implements PhaseListener {

	private static def ExcludesPages = ["login.xhtml", "lockdown.xhtml"]

	AuthorizationListener() {
		super()
	}

	@Override
	void afterPhase(PhaseEvent event) {
		def currentPage = event.facesContext.getViewRoot().getViewId()
		def isExcludesPage = ExcludesPages.any { currentPage.endsWith(it) }
		def session = FacesContext.currentInstance.externalContext.getSession(true) as HttpSession
		Boolean isLoggedIn = session.getAttribute("loggedin")
		Boolean isLockDown = session.getAttribute("lockdown")

		if (!isExcludesPage && !isLoggedIn) {
			event.facesContext.application.navigationHandler.handleNavigation(
				event.facesContext, null,
				"login"
			)
		}
		if (!isExcludesPage && isLoggedIn && isLockDown) {
			event.facesContext.application.navigationHandler.handleNavigation(
				event.facesContext, null,
				"lockdown"
			)
		}
	}

	@Override
	void beforePhase(PhaseEvent event) {

	}

	@Override
	PhaseId getPhaseId() {
		PhaseId.RESTORE_VIEW
	}
}
